;; Run with:
;;     guile -s FILE ~/.guix-profile

(use-modules (guix profiles)
             (gnu packages)             ; fold-packages
             (guix packages)            ; package structure
             (ice-9 match)
             (ice-9 pretty-print))


(define (packages-by-name name)
  (fold-packages (lambda (package list)
                   (if (string=? (package-name package) name)
                       (cons package list)
                       list))
                 '()))

(define (guix-manifest where)
  (sort (map (lambda (entry)
               (let* ((name (manifest-entry-name entry))
                      (out (manifest-entry-output entry))
                      (version (manifest-entry-version entry))
                      (default-version (match (packages-by-name name)
                                         ((first-name . rest)
                                          (package-version
                                           first-name))
                                         (else #f))))
                 (string-append name
                                (if (and default-version
                                         (not (string= version default-version)))
                                    (format #f "@~a" version)
                                    "")
                                (if (string= out "out")
                                    ""
                                    (format #f ":~a" out)))))
             (manifest-entries (profile-manifest where)))
        string<?))

;; Thanks to Ivan Vilata-i-Balaguer for this:
(define (guix-commit)
  (let ((guix-manifest (profile-manifest (string-append (getenv "HOME") "/.config/guix/current"))))
    (match (assq 'source (manifest-entry-properties (car (manifest-entries guix-manifest))))
      (('source ('repository ('version 0) _ _
                             ('commit commit) _ ...))
       commit)
      (_ #f))))

(match (command-line)
  ((_ where)
   (format #t ";; commit: ~a\n" (guix-commit))
   (pretty-print
    `(specifications->manifest
      ',(guix-manifest where))))
  (_ (error "Please provide the path to a Guix profile.")))
